﻿#include "widget.h"
#include "ui_widget.h"
#include <QUrl>
#include <QQmlEngine>
#include <QDesktopWidget>
#include <QQmlContext>
#include <QPalette>
#include <QPixmap>
#include <QBrush>
#include <QColor>
#include <QIcon>
#include <QMenu>
#include <QAction>
#include <QTimer>
#include <QSettings>
#include <QApplication>
#include <QDebug>
#include <stdio.h>
#include <QDir>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);


    setWindowFlags(this->windowFlags() /*| Qt::WindowStaysOnTopHint*/ | Qt::SubWindow | Qt::FramelessWindowHint);

    //背景透明
    setAttribute(Qt::WA_TranslucentBackground);

    //填充背景
    setAutoFillBackground(true);

    //画刷

    QPalette palette;
    palette.setColor(QPalette::Background, QColor(0x00, 0xFF, 0x00, 0x00));
    setPalette(palette);

    //qml透明
    ui->quickWidget->setAttribute(Qt::WA_TranslucentBackground);
    ui->quickWidget->setClearColor(QColor(Qt::transparent));

    ui->quickWidget->engine()->rootContext()->setContextProperty("widget",this);

    ui->quickWidget->engine()->addImportPath(QDir::currentPath());

    ui->quickWidget->setSource(QUrl("qrc:/main.qml"));

    setSystemMenu();

    setGeometry(0,0,1,1);

    QTimer::singleShot(1000, this, &Widget::init);

    autoRun2(true);

}

Widget::~Widget()
{
    delete ui->quickWidget;
    delete ui;
}
//添加系统托盘
void Widget::setSystemMenu()
{
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/logo.ico"));

    QMenu *menu = new QMenu(this);
    QAction *action = menu->addAction("退出");
    connect(action, &QAction::triggered, this, &Widget::systemExit);

    trayIcon->setContextMenu(menu);
    trayIcon->show();
}

void Widget::systemExit(bool b)
{
    qApp->quit();
}

void Widget::init()
{
    setWindowState(Qt::WindowMaximized);
    setGeometry(0,0,QApplication::desktop()->width(),QApplication::desktop()->height()+1);
}
//设置开机启动
void Widget::autoRun(bool run)
{
    QString path = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

    QString exePath = QApplication::applicationFilePath();
    exePath = exePath.replace("/", "\\");

    QSettings *reg = new QSettings(path, QSettings::NativeFormat);

    if(run){
        reg->setValue("rest", exePath);
    }
    else{
        reg->setValue("rest", "");
    }
}

void Widget::autoRun2(bool run)
{
    HKEY hKey;
    HKEY subKey;
    DWORD result;
    char *path = QApplication::applicationFilePath().replace("/", "\\").toLatin1().data();
    char pathArr[] = "4.0";
    int len = strlen(path);
    LPBYTE lpData = new BYTE[len+1];


    if(run){
        for(int i=0; i<len; i++){
            *(lpData+i) = path[i];
        }
    }
    else{
        *(lpData) = 0;
    }
    //因为unicode编码下直接转成LPBYTE结果只剩第一个字符。也就是说把unicode编码转成ANSI编码就能正确转换了

    //打开注册表
    result = RegOpenKeyEx(
                HKEY_LOCAL_MACHINE, //本机注册表（要打开的注册表）
                TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
                0,              //保留参数必须填 0
                KEY_SET_VALUE,  //打开权限，写入
                &hKey           //打开之后的句柄
                );

    if(result == ERROR_SUCCESS){
        //注册表打开成功
        qDebug()<<"注册表打开成功";
    }
    else{
        //注册表打开失败
        qDebug()<<"注册表打开失败";
        return;
    }

    //在注册表中设置(没有则会新增一个值)
    result = RegSetValueExA(
                hKey,
                (LPCSTR)(QString("rest").toLocal8Bit().constData()),                     //键名
                0,                          //保留参数必须填 0
                REG_SZ,                     // 键值类型为字符串
                lpData,
                len
                );
    if(result == ERROR_SUCCESS){
        //注册表设置成功
        qDebug()<<"注册表设置成功";
    }
    else{
        //注册表设置失败
        qDebug()<<"注册表设置失败";
    }

    RegCloseKey(hKey);
}

void Widget::QueryKey(HKEY hKey)
{
    TCHAR    achKey[MAX_KEY_LENGTH];   // buffer for subkey name
    DWORD    cbName;                   // size of name string
    TCHAR    achClass[MAX_PATH] = TEXT("");  // buffer for class name
    DWORD    cchClassName = MAX_PATH;  // size of class string
    DWORD    cSubKeys = 0;             // number of subkeys
    DWORD    cbMaxSubKey;              // longest subkey size
    DWORD    cchMaxClass;              // longest class string
    DWORD    cValues;              // number of values for key
    DWORD    cchMaxValue;          // longest value name
    DWORD    cbMaxValueData;       // longest value data
    DWORD    cbSecurityDescriptor; // size of security descriptor
    FILETIME ftLastWriteTime;      // last write time

    DWORD i, retCode;

    TCHAR  achValue[MAX_VALUE_NAME];
    DWORD cchValue = MAX_VALUE_NAME;

    // Get the class name and the value count.
    retCode = RegQueryInfoKey(
                hKey,                    // key handle
                achClass,                // buffer for class name
                &cchClassName,           // size of class string
                NULL,                    // reserved
                &cSubKeys,               // number of subkeys
                &cbMaxSubKey,            // longest subkey size
                &cchMaxClass,            // longest class string
                &cValues,                // number of values for this key
                &cchMaxValue,            // longest value name
                &cbMaxValueData,         // longest value data
                &cbSecurityDescriptor,   // security descriptor
                &ftLastWriteTime);       // last write time

    // Enumerate the subkeys, until RegEnumKeyEx fails.

    if (cSubKeys)
    {

        for (i = 0; i < cSubKeys; i++)
        {
            cbName = MAX_KEY_LENGTH;
            retCode = RegEnumKeyEx(hKey, i,
                                   achKey,
                                   &cbName,
                                   NULL,
                                   NULL,
                                   NULL,
                                   &ftLastWriteTime);
            if (retCode == ERROR_SUCCESS)
            {
                printf((" %sn"), achKey);
            }
        }
    }

    // Enumerate the key values.

    if (cValues)
    {

        for (i = 0, retCode = ERROR_SUCCESS; i < cValues; i++)
        {
            cchValue = MAX_VALUE_NAME;
            achValue[0] = '\0';
            retCode = RegEnumValue(hKey, i,
                                   achValue,
                                   &cchValue,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL);

            if (retCode == ERROR_SUCCESS )
            {
                printf((" %sn"), achValue);
            }
        }
    }
}
